const pool = require('../db');

class Software {
  static async getAllSoftware() {
    try {
      const [rows] = await pool.execute('SELECT * FROM software');
      return rows;
    } catch (error) {
      throw new Error(`获取软件列表失败: ${error.message}`);
    }
  }

  static async getSoftwareById(id) {
    try {
      const [rows] = await pool.execute('SELECT * FROM software WHERE id = ?', [id]);
      return rows[0] || null;
    } catch (error) {
      throw new Error(`获取软件详情失败: ${error.message}`);
    }
  }

  static async createSoftware(softwareData) {
    const { name, version, description, category, file_path, file_size, download_count, cover_image } = softwareData;
    try {
      const [result] = await pool.execute(
        'INSERT INTO software (name, version, description, category, file_path, file_size, download_count, cover_image, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())',
        [name, version, description, category, file_path, file_size, download_count || 0, cover_image]
      );
      return { id: result.insertId, ...softwareData };
    } catch (error) {
      throw new Error(`创建软件记录失败: ${error.message}`);
    }
  }

  static async updateSoftware(id, softwareData) {
    const { name, version, description, category, file_path, file_size, cover_image } = softwareData;
    try {
      await pool.execute(
        'UPDATE software SET name = ?, version = ?, description = ?, category = ?, file_path = ?, file_size = ?, cover_image = ?, updated_at = NOW() WHERE id = ?',
        [name, version, description, category, file_path, file_size, cover_image, id]
      );
      return { id, ...softwareData };
    } catch (error) {
      throw new Error(`更新软件记录失败: ${error.message}`);
    }
  }

  static async incrementDownloadCount(id) {
    try {
      await pool.execute('UPDATE software SET download_count = download_count + 1 WHERE id = ?', [id]);
      return true;
    } catch (error) {
      throw new Error(`增加下载计数失败: ${error.message}`);
    }
  }

  static async deleteSoftware(id) {
    try {
      await pool.execute('DELETE FROM software WHERE id = ?', [id]);
      return true;
    } catch (error) {
      throw new Error(`删除软件记录失败: ${error.message}`);
    }
  }
}

module.exports = Software;